package com.pengpeng.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.pengpeng.jwt.constant.JWTConstant;

import java.util.Calendar;
import java.util.Map;

/**
 * Describe:
 * Created by AlexP on 2021/11/18.
 */
public class JWTUtils {

    /**
     * 生成token
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);

        //默认十分钟过期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 10);

        //指定令牌过期时间
        builder.withExpiresAt(calendar.getTime());
        //签名策略
        return builder.sign(Algorithm.HMAC256(JWTConstant.SECRET));
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        //如果有异常会抛出
        return JWT.require(Algorithm.HMAC256(JWTConstant.SECRET)).build().verify(token);
    }
}
